package com.wzdigit.wms.wms.rpc.oqc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.oqc.OqcInsp;
import com.wzdigit.wms.basic.domain.oqc.OqcInspDtl;
import com.wzdigit.wms.basic.enums.OqcInspDtlStatusEnum;
import com.wzdigit.wms.basic.enums.OqcInspStatusEnum;
import com.wzdigit.wms.basic.enums.QaStatusEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.oqc.OqcInspDtlMapper;
import com.wzdigit.wms.basic.mapper.core.oqc.OqcInspMapper;
import com.wzdigit.wms.common.utils.MyListUtil;
import com.wzdigit.wms.wms.api.oqc.OqcInspApi;
import com.wzdigit.wms.wms.dto.oqc.OqcInspDtlDto;
import com.wzdigit.wms.wms.dto.oqc.OqcInspDto;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName OqcInspApiImplService
 * @Description oqc判检接口实现类
 * @Author LHR-PC
 * @Date 2021/1/24 22:39
 * @Version
 **/
@Service(version = "${dubbo.providers.wms.oqcInsp.api:1.0.0}")
@Slf4j
//@Component
public class OqcInspApiImplService implements OqcInspApi {

    @Autowired
    private OqcInspMapper oqcInspMapper;

    @Autowired
    private OqcInspDtlMapper oqcInspDtlMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<Integer> batchInsert(List<OqcInspDto> oqcInspDtoList) {

        log.info("送检单判检回写接口");
        log.info("入参大小：" + String.valueOf(oqcInspDtoList.size()));
        log.info(oqcInspDtoList.toString());

//        for (OqcInspDto oqcInspDto : oqcInspDtoList) {
//            oqcInspDto.setOqcInspId(oqcInspDto.getQmsOqcId());
//        }
//        log.info("更新后的入参："+oqcInspDtoList.toString());


        List<Integer> failureIds = new ArrayList<>();
        for (OqcInspDto oqcInspDto : oqcInspDtoList) {
//            try {
            log.info("["+oqcInspDto.getInspNo()+"]"+"SN数量:"+oqcInspDto.getOqcInspDtlDtoList().size());
            OqcInsp oqcInsp = new OqcInsp();
//            oqcInspDto.setOqcInspId(oqcInspDto.getQmsOqcId());
            BeanUtil.copyNonNull(oqcInspDto, oqcInsp);
//            oqcInsp.setOqcInspId(oqcInspDto.getQmsOqcId());//加个主键

//            log.info("oqcInspDto:"+oqcInspDto.toString());
//            log.info("-------------------------------------");


            if (oqcInspDto.getSkuCode() != null) {
                Sku sku = new Sku();
                sku.setSkuCode(oqcInspDto.getSkuCode());
                Sku record = skuMapper.selectOne(new QueryWrapper<>(sku));
                if (record != null) {
                    oqcInsp.setSkuDesc(record.getDescCn());
                }
            }

            //判检结果，151 = 1合格，152 = 2不合格
            if (oqcInspDto.getInspResult().equals(151)) {
                oqcInsp.setInspResult(QaStatusEnum.OK.getCode());
            } else if (oqcInspDto.getInspResult().equals(152)) {
                oqcInsp.setInspResult(QaStatusEnum.NG.getCode());
            } else {
                oqcInsp.setInspResult(oqcInspDto.getInspResult());
            }
            OqcInsp record = oqcInspMapper.selectByInspNo(oqcInspDto.getInspNo());
            boolean falg = (record == null);
            log.info("record为null？"+falg);
            //送检单号(INSP_NO)作为Key值，判断单据是否已经存在
            if (record != null && record.getInspNo() != null && !record.getInspResult().equals(oqcInspDto.getInspResult())) {
                /**
                 * 若送检单号存在，并且判检结果有变化，则更新送货单，同时更新送货单明细
                 * 主档状态=0，明细状态(全部) = 0
                 * 判检结果：根据同步过来判检结果
                 */
                oqcInsp.setModifyTime(new Date());
                oqcInsp.setModifyUser("system");
                oqcInsp.setStatus(OqcInspStatusEnum.OQC_STATUS_UN_HANDLE.getCode());
                oqcInsp.setOqcInspId(record.getOqcInspId());
                oqcInspMapper.updateById(oqcInsp);
                List<OqcInspDtlDto> oqcInspDtlDtoList = oqcInspDto.getOqcInspDtlDtoList();
                if (!CollectionUtil.isEmpty(oqcInspDtlDtoList)) {

                    List<String> snList = oqcInspDtlDtoList.stream().map(s -> s.getGoodsSn()).collect(Collectors.toList());
                    List<OqcInspDtl> oqcInspDtls = new ArrayList<>();
                    //处理SQL1000异常
                    if (snList.size()>1000) {
                        List<List<String>> splitList = MyListUtil.splitList(snList, 999);
                        for (List<String> list : splitList) {
                            oqcInspDtls.addAll(oqcInspDtlMapper.selectBySnList(list));
                        }
                    } else {
                        oqcInspDtls = oqcInspDtlMapper.selectBySnList(snList);
                    }

                    int unHandleCode = OqcInspDtlStatusEnum.OQCDTL_STATUS_UN_HANDLE.getCode();

                    //单个更新
//                    for (OqcInspDtl oqcInspDtl : oqcInspDtls) {
//                        oqcInspDtl.setModifyUser("system");
//                        oqcInspDtl.setModifyTime(new Date());
//                        oqcInspDtl.setStatus(unHandleCode);
//                        oqcInspDtlMapper.updateById(oqcInspDtl);
//                    }
                    //单个更新

                    //批量更新
                    List<Integer> oqcInspDtlIds = oqcInspDtls.stream().map(s -> s.getOqcInspDtlId()).collect(Collectors.toList());

                    //处理SQL的in1000
                    if (oqcInspDtlIds.size() > 1000) {
                        List<List<Integer>> splitList = MyListUtil.splitList(oqcInspDtlIds, 999);
                        for (List<Integer> split : splitList) {
                            Integer row = oqcInspDtlMapper.updateByOqccInspDtlIdList("system", new Date(), unHandleCode, split);
                            log.info("成功更新{}条记录",row);
                        }
                    } else {
                        Integer row = oqcInspDtlMapper.updateByOqccInspDtlIdList("system", new Date(), unHandleCode, oqcInspDtlIds);
                        log.info("成功更新{}条记录",row);
                    }
                    //批量更新




                    oqcInspDtlDtoList = oqcInspDtlDtoList.stream().filter(s->!snList.contains(s.getGoodsSn())).collect(Collectors.toList());
                    for (OqcInspDtlDto oqcInspDtlDto : oqcInspDtlDtoList) {
                        OqcInspDtl oqcInspDtl = new OqcInspDtl();

                        oqcInspDtl.setCreateUser("system");
                        oqcInspDtl.setCreateTime(new Date());
                        oqcInspDtl.setStatus(OqcInspDtlStatusEnum.OQCDTL_STATUS_UN_HANDLE.getCode());
                        oqcInspDtl.setGoodsSn(oqcInspDtlDto.getGoodsSn());
                        oqcInspDtl.setOqcInspId(record.getOqcInspId());//加个主表主键
                        oqcInspDtlMapper.insert(oqcInspDtl);
                    }



//                    for (OqcInspDtlDto oqcInspDtlDto : oqcInspDtlDtoList) {
//                        OqcInspDtl record2 = oqcInspDtlMapper.selectBySn(oqcInspDtlDto.getGoodsSn());
//                        OqcInspDtl oqcInspDtl = new OqcInspDtl();
//                        BeanUtil.copyNonNull(oqcInspDtlDto, oqcInspDtl);
////                        oqcInspDtl.setOqcInspId(oqcInspDtlDto.getOqcInspId());
//                        if (record2 != null) {
//                            oqcInspDtl.setModifyUser("system");
//                            oqcInspDtl.setModifyTime(new Date());
//                            oqcInspDtl.setStatus(OqcInspDtlStatusEnum.OQCDTL_STATUS_UN_HANDLE.getCode());
//                            oqcInspDtl.setOqcInspDtlId(record2.getOqcInspDtlId());
//                            oqcInspDtlMapper.updateById(oqcInspDtl);
//                        } else {
//                            oqcInspDtl.setCreateUser("system");
//                            oqcInspDtl.setCreateTime(new Date());
//                            oqcInspDtl.setStatus(OqcInspDtlStatusEnum.OQCDTL_STATUS_UN_HANDLE.getCode());
//                            log.info("插入1："+ oqcInspDtl.toString());
//                            oqcInspDtl.setOqcInspId(record.getOqcInspId());//加个主表主键
//                            oqcInspDtlMapper.insert(oqcInspDtl);
//                        }
//                    }
                }
            } else {
                /**
                 * 若送检单号不存在，则新插入送货单号，同时插入送货单明细。
                 * 主档状态=0，明细状态(全部) = 0
                 * 判检结果：根据同步过来判检结果
                 */
                oqcInsp.setCreateTime(new Date());
                oqcInsp.setCreateUser("system");
                oqcInsp.setStatus(OqcInspStatusEnum.OQC_STATUS_UN_HANDLE.getCode());
                log.info("插入2："+ oqcInsp.toString());
                oqcInspMapper.insert(oqcInsp);
                System.out.println(oqcInsp);
                List<OqcInspDtlDto> oqcInspDtlDtoList = oqcInspDto.getOqcInspDtlDtoList();
                if (!CollectionUtil.isEmpty(oqcInspDtlDtoList)) {
                    for (OqcInspDtlDto oqcInspDtlDto : oqcInspDtlDtoList) {
                        OqcInspDtl oqcInspDtl = new OqcInspDtl();
                        BeanUtil.copyNonNull(oqcInspDtlDto, oqcInspDtl);
                        oqcInspDtl.setCreateUser("system");
                        oqcInspDtl.setCreateTime(new Date());
                        oqcInspDtl.setStatus(OqcInspDtlStatusEnum.OQCDTL_STATUS_UN_HANDLE.getCode());
                        oqcInspDtl.setOqcInspId(oqcInsp.getOqcInspId());//设置主键ID
                        oqcInspDtlMapper.insert(oqcInspDtl);
                    }
                }
            }
//            } catch (Exception e) {
//                e.printStackTrace();
//                failureIds.add(oqcInspDto.getOqcInspId());
//            }
        }
        //TODO 测试代码，测试和投产记得删除
//        int a = 0 / 0;
        log.info("处理【送检单判检回写接口】结束");
        return failureIds;
    }
}
